define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var disburse = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "财务打款") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initCity();
            this.initTable();
            this.bindEvent();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function () {
            $('#table').DataTable().ajax.reload();
        },
        /**
         * 初始化的列表
         */
        initTable: function () {
            var self = this;
            var table = $("#table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": false, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/centralbank/caiwu/queryDisburseRecord'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    var _data = {};
                    _data.pageNo = aoData[3].value / aoData[4].value + 1;
                    _data.pageSize = aoData[4].value;
                    CRM.request({
                        "type": 'GET',
                        "url": sSource,
                        "dataType": "json",
                        contentType: "application/x-www-form-urlencoded",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": _data,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = 9999999;
                                    resultData.iTotalRecords = 9999999;
                                    $.each(req.entry, function (key, entry) {
                                        resultData.aaData.push(entry)
                                    });
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                }, //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [
                    {
                        "sTitle": "打款单",
                        "mDataProp": "desc",
                        "bSortable": true
                    },
                    {
                        "sTitle": "操作",
                        "bSortable": true,
                        "mRender": function (data, type, row) {
                            var _returnStr = "";
                            if (row.status == 2 || row.status == 3) {
                                _returnStr += '<a type="button" class="btn btn-info" href="' + CRM.getOuterUrl('/centralbank/caiwu/downloadToBePaidSellerReceivableBillForICBC?disburseRecordId=' + row.id) + '" target="_blank">下载打款单</a> ';
                            }
                            if (row.version == 0) {
                                if (row.status == 2) {
                                    _returnStr += '<span class="btn btn-success fileinput-button"><i class="glyphicon glyphicon-plus"></i><span>上传回执单</span>';
                                    _returnStr += '<input id="file_' + row.id + '" data="' + row.id + '" type="file" name="file" multiple=""></span>';
                                }
                            } else {
                                if (row.caiOpStatus == 1) {
                                    _returnStr += '<a type="button" class="btn btn-warning" href="javascript:firstCheck(\'' + row.id + '\')">初审</a> ';
                                } else if (row.caiOpStatus == 2) {
                                    _returnStr += '<a type="button" class="btn btn-danger" href="javascript:disburseByCmb(\'' + row.id + '\')">确认打款</a> ';
                                } else if (row.caiOpStatus == 3) {
                                    _returnStr += '<a type="button" class="btn btn-primary" href="' + CRM.getOuterUrl('/centralbank/caiwu/downloadReceipt?disburseRecordId=' + row.id) + '" target="_blank">下载回执单</a> ';
                                }
                            }


                            return _returnStr;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "simple" //分页，一共两种样式，full_numbers和two_button(默认)

            });
            table.on('draw.dt', function () {
                try {
                    self.initUpload();
                } catch (e) {
                    console.log(e)
                }
            });
        },
        /**
         * 城市初始化
         */
        initCity: function () {
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/shop/city/queryOpenCity'),
                "dataType": "json",
                contentType: "application/json",
                data: JSON.stringify({}),
                "success": function (req) {
                    if (req.status) {
                        $.each(req.entry, function (index, item) {
                            $("#cityCode").append("<option value='" + item.cityCode + "'>" + item.city + "</option>");
                        });
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 生成打款单
         */
        disburse: function () {
            var self = this;
            var _data = {};
            $($("#form").serializeArray()).each(function () {//获取查询条件
                _data[this.name] = this.value;
            });
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl('/centralbank/caiwu/genDisburseRecord'),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                xhrFields: {
                    withCredentials: true
                },
                "data": _data,
                contentType: "application/json",
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                        self.doSearch();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 初审
         * @param disburseRecordId
         */
        firstCheck: function (disburseRecordId) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl('/centralbank/caiwu/firstCheck'),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                xhrFields: {
                    withCredentials: true
                },
                "data": {
                    disburseRecordId: disburseRecordId
                },
                contentType: "application/json",
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                        self.doSearch();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 确认打款
         * @param disburseRecordId
         */
        disburseByCmb: function (disburseRecordId) {
            var self = this;
            CRM.showConfirm("请确保打款账户中可用余额充足", function () {
                CRM.request({
                    "type": 'GET',
                    "url": CRM.getOuterUrl('/centralbank/caiwu/disburseByCmb'),
                    "dataType": "json",
                    contentType: "application/x-www-form-urlencoded",
                    xhrFields: {
                        withCredentials: true
                    },
                    "data": {
                        disburseRecordId: disburseRecordId
                    },
                    contentType: "application/json",
                    "success": function (req) {
                        if (req.status) {
                            CRM.showDialog(req.message);
                            self.doSearch();
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            })
        },
        bindEvent: function () {
            var self = this;
            $("#disburse").on('click', function () {
                self.disburse();
            });

        },
        /**
         * 初始化上传
         */
        initUpload: function () {
            $("input[id^='file_']").each(function (index, item) {
                var _id = $(item).attr("data");
                $(item).fileupload({
                    url: CRM.getOuterUrl('/centralbank/caiwu/uploadDisburseRecorde'),//文件上传地址，当然也可以直接写在input的data-url属性内
                    formData: {bankDisburseRecordId: _id},//如果需要额外添加参数可以在这里添加
                    done: function (e, req) {
                        //done方法就是上传完毕的回调函数，其他回调函数可以自行查看api
                        //注意result要和jquery的ajax的data参数区分，这个对象包含了整个请求信息
                        //返回的数据在result.result中，假设我们服务器返回了一个json对象
                        if (req.result.status) {
                            CRM.showDialog(req.result.message);
                            $('#table').DataTable().ajax.reload();
                        } else {
                            CRM.showDialog(req.result.message);
                        }

                    }
                });
            })
        }
    };

    window.disburse = $.proxy(disburse.disburse, disburse);
    window.firstCheck = $.proxy(disburse.firstCheck, disburse);
    window.disburseByCmb = $.proxy(disburse.disburseByCmb, disburse);

    disburse.init();
});